package api

import (
	"AiSpeaker/constant"
	"AiSpeaker/internal/aiRequestHandler"
	"AiSpeaker/internal/domain"
	"AiSpeaker/pkg/logger"
	"encoding/json"
	"github.com/gofiber/fiber/v2"
	"strings"
)

func AlarmMessageHandler(app *fiber.App) {
	app.Post("/system/aibox/accept", func(c *fiber.Ctx) error {
		bodyParams := c.BodyRaw()

		aiBoxRequest := &domain.AiBoxRequest{}
		err := json.Unmarshal(bodyParams, aiBoxRequest)
		if err != nil {
			logger.Errorf("解析事件内容出错，原因：%s", err.Error())
			resp := &domain.Response{
				Code: constant.DefaultHttpErrorResponseCode,
				Msg:  err.Error(),
			}
			return c.JSON(resp)
		}

		/*
		 * 根据算法大类获取对应的处理类
		 */
		aiType := aiBoxRequest.Type
		logger.Infof("算法大类：%s", aiType)
		if strings.ToLower(aiType) == "heartbeat" {
			resp := &domain.Response{
				Code: constant.DefaultResponseCode,
			}
			return c.JSON(resp)
		}
		handler := aiRequestHandler.GlobalAiRequestHandlerMap[strings.ToLower(aiType)]

		if handler != nil {
			/*
			 * 通过解析cameraOutId，获取音柱id
			 */
			cameraOutId := strings.Split(aiBoxRequest.CameraOutId, "-")
			logger.Infof("cameraOutId：%s", cameraOutId)
			if len(cameraOutId) == 3 && strings.ToUpper(cameraOutId[1]) == "Y" {
				handler.Handler(aiBoxRequest, aiType, cameraOutId[2])
			}
		} else {
			logger.Errorf("没有找到对应算法的处理类，算法大类:[%s]", aiType)
			resp := &domain.Response{
				Code: constant.DefaultHttpErrorResponseCode,
				Msg:  "没有找到处理类",
			}
			return c.JSON(resp)
		}

		resp := &domain.Response{
			Code: constant.DefaultResponseCode,
		}
		return c.JSON(resp)
	})
}
